<?php

namespace App\Http\Controllers\Api;

use App\Models\Brand;
use App\Models\Product;
use App\Models\UserProducts;
use App\Http\Requests\Api\UserProductsRequest;
use Illuminate\Support\Facades\DB;

class UserProductsController extends Controller
{
    public function store(UserProductsRequest $request, UserProducts $userProducts)
    {
        $user = $this->user();

        DB::transaction(function () use ($userProducts, $user, $request){
            $userProducts->user_id = $user->id;
            $userProducts->product_ids = implode(',', $request->product_ids);
            $userProducts->save();

            // 更新选中的产品统计数
            Product::query()->whereIn('id', $request->product_ids)->increment('picked_count');


            // 更新选中的品牌统计数
            $brandIds = Product::query()->whereIn('id', $request->product_ids)->pluck('brand_id');
            Brand::query()->whereIn('id', $brandIds->all())->increment('picked_count');

        });

        return response()->json([
            'code' => 200,
            'message' => 'success',
        ]);
    }
}
